<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>订单列表</title>
    <!-- 引入WeUI CSS -->
    <link rel="stylesheet" href="./weui/weui.min.css">
    <style>
        /* 全局样式 */
        body {
            background-color: #f5f5f5;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            padding-bottom: 100px; /* 为固定按钮留出空间 */
        }
        
        .page-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 15px;
        }
        
        /* 头部样式 */
        .header {
            text-align: center;
            margin-bottom: 25px;
            padding: 25px 0 15px;
            position: relative;
        }
        
        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 4px;
            background: linear-gradient(to right, #07C160, #10a5c5);
            border-radius: 2px;
        }
        
        .header-title {
            font-size: 26px;
            color: #333;
            font-weight: 600;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }
        
        /* 添加订单按钮 - 固定在右下角 */
        .add-order-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: auto;
            min-width: 160px;
            background: linear-gradient(to right, #07C160, #10a5c5);
            color: white;
            border: none;
            border-radius: 50px;
            padding: 15px 25px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 6px 20px rgba(7, 193, 96, 0.3);
            text-align: center;
            z-index: 99;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .add-order-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(7, 193, 96, 0.4);
        }
        
        .add-order-btn:active {
            transform: translateY(-1px);
        }
        
        /* 订单卡片样式 */
        .order-card {
            background-color: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
        }
        
        .order-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
        }
        
        .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .order-number {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }
        
        .order-status {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-completed {
            background-color: #32CD32;
            color: white;
        }
        
        .status-pending {
            background-color: #FFD700;
            color: #333;
        }
        
        .order-time {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
        
        .order-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        
        .order-section {
            margin-bottom: 15px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
        }
        
        .section-title::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 14px;
            background: linear-gradient(to bottom, #07C160, #10a5c5);
            border-radius: 2px;
            margin-right: 8px;
        }
        
        .company-info {
            margin-bottom: 10px;
        }
        
        .company-name {
            font-weight: 500;
            color: #333;
            margin-bottom: 5px;
        }
        
        .weight-info {
            font-size: 14px;
            color: #666;
        }
        
        .weight-value {
            font-weight: 500;
            color: #07C160;
        }
        
        /* 图片预览容器 */
        .photo-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .photo-preview-item {
            width: calc(33.333% - 8px);
            border: 1px solid #eee;
            border-radius: 6px;
            overflow: hidden;
        }
        
        .photo-preview-item img {
            width: 100%;
            height: 80px;
            object-fit: contain;
            cursor: pointer;
        }
        
        /* 操作按钮区域 */
        .order-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #f0f0f0;
        }
        
        .detail-btn {
            background: linear-gradient(to right, #07C160, #10a5c5);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 10px 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .detail-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        
        .detail-btn:active {
            transform: translateY(0);
        }
        
        /* 大图预览模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            overflow: auto;
            touch-action: manipulation;
        }
        
        .modal-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 20px;
        }
        
        .modal-img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
            -webkit-user-select: none;
            user-select: none;
        }
        
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        
        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-icon {
            font-size: 60px;
            margin-bottom: 20px;
            color: #ddd;
        }
        
        .empty-text {
            font-size: 16px;
            margin-bottom: 20px;
        }
        
        /* 加载状态 */
        .loading-state {
            text-align: center;
            padding: 20px;
            color: #999;
        }
        
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(7, 193, 96, 0.2);
            border-radius: 50%;
            border-top-color: #07C160;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        /* 没有更多数据 */
        .no-more-data {
            text-align: center;
            padding: 20px;
            color: #999;
            font-size: 14px;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .add-order-btn {
                bottom: 20px;
                right: 20px;
                min-width: 140px;
                padding: 12px 20px;
                font-size: 14px;
            }
            
            .page-container {
                padding-bottom: 80px;
            }
        }
        
        @media (max-width: 480px) {
            .header-title {
                font-size: 22px;
            }
            
            .order-content {
                grid-template-columns: 1fr;
            }
            
            .photo-preview-item {
                width: calc(50% - 8px);
            }
            
            .order-actions {
                flex-direction: column;
            }
            
            .add-order-btn {
                bottom: 15px;
                right: 15px;
                min-width: 120px;
                padding: 10px 15px;
                font-size: 13px;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
        <div class="header">
            <h1 class="header-title">订单列表📋</h1>
        </div>
        
        <!-- 订单列表 -->
        <div id="orderList">
            <div class="loading-state">
                <div class="loading-spinner"></div>
                正在加载订单数据...
            </div>
        </div>
        
        <!-- 加载更多状态 -->
        <div id="loadingMore" class="loading-state" style="display: none;">
            <div class="loading-spinner"></div>
            正在加载更多订单...
        </div>
        
        <!-- 没有更多数据 -->
        <div id="noMoreData" class="no-more-data" style="display: none;">
            没有更多订单数据了
        </div>
    </div>

    <!-- 添加订单按钮 - 固定在右下角 -->
    <button class="add-order-btn" id="addOrderBtn">
        <span style="font-size: 18px;">+</span> 添加起点订单
    </button>

    <!-- 大图预览模态框 -->
    <div id="imageModal" class="modal">
        <span class="close">&times;</span>
        <div class="modal-content">
            <img id="modalImage" class="modal-img">
        </div>
    </div>

    <!-- 引入WeUI JS -->
    <script src="./weui/weui.min.js"></script>
    <script src="./weui/axios.min.js"></script>
    <script src="./axios.js"></script> 
    <script src="./wechat-auth.js"></script>
    <script src="./api.js"></script>
    <script>
        // 分页相关变量
        let currentPage = 1;
        const pageSize = 10;
        let isLoading = false;
        let hasMore = true;
        let allOrders = [];

        // 获取状态对应的CSS类和文本
        function getStatusInfo(status) {
            if (status == 1) {
                return {
                    class: 'status-completed',
                    text: '已完成'
                };
            } else if (status == 2) {
                return {
                    class: 'status-pending',
                    text: '未完成'
                };
            } else {
                return {
                    class: '',
                    text: '未知状态'
                };
            }
        }

        // 格式化日期时间
        function formatDateTime(timestamp) {
            if (!timestamp) return '';
            // Unix 时间戳（秒）转换为 JavaScript 时间戳（毫秒）
            const date = new Date(timestamp * 1000);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }

        // 显示大图预览
        function showLargePreview(imageSrc) {
            const modal = document.getElementById('imageModal');
            const modalImg = document.getElementById('modalImage');
            
            modal.style.display = "block";
            modalImg.src = imageSrc;
            
            // 禁用滚动
            document.body.style.overflow = 'hidden';
        }

        // 关闭大图预览
        document.querySelector('.close').onclick = function() {
            document.getElementById('imageModal').style.display = "none";
            document.body.style.overflow = 'auto';
        };

        // 点击模态框背景关闭
        document.getElementById('imageModal').onclick = function(event) {
            if (event.target === this) {
                this.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        };

        // 查看订单详情
        function viewOrderDetail(orderId) {
            if (!orderId) {
                weui.toast('请先选择订单', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
                return;
            }
            
            // 跳转到订单详情页面，传递订单ID
            window.location.href = `/detail.html?order_id=${orderId}`;
        }

        // 添加起点订单
        function addStartOrder() {
            // 跳转到添加起点订单页面
            window.location.href = `/startWrite.html`;
        }

        // 渲染订单列表
        function renderOrderList(orders, append = false) {
            const orderList = document.getElementById('orderList');
            
            if (!orders || orders.length === 0) {
                if (!append) {
                    orderList.innerHTML = `
                        <div class="empty-state">
                            <div class="empty-icon">📦</div>
                            <div class="empty-text">暂无订单数据</div>
                        </div>
                    `;
                }
                return;
            }
            
            let ordersHtml = '';
            
            if (!append) {
                ordersHtml = '';
            }
            
            orders.forEach(order => {
                const statusInfo = getStatusInfo(order.status);
                
                // 处理起点图片数据
                let startImagesHtml = '';
                if (order.images && Array.isArray(order.images) && order.images.length > 0) {
                    startImagesHtml = `
                        <div class="photo-preview-container">
                            ${order.images.slice(0, 3).map((imageUrl, index) => `
                                <div class="photo-preview-item">
                                    <img src="${imageUrl}" alt="货物照片 ${index + 1}" onclick="showLargePreview('${imageUrl}')">
                                </div>
                            `).join('')}
                            ${order.images.length > 3 ? `<div class="photo-preview-item" style="display: flex; align-items: center; justify-content: center; background: #f0f0f0; color: #999; font-size: 12px;">+${order.images.length - 3}</div>` : ''}
                        </div>
                    `;
                }
                
                // 处理终点图片数据
                let endImagesHtml = '';
                if (order.pid && order.pid.images && Array.isArray(order.pid.images) && order.pid.images.length > 0) {
                    endImagesHtml = `
                        <div class="photo-preview-container">
                            ${order.pid.images.slice(0, 3).map((imageUrl, index) => `
                                <div class="photo-preview-item">
                                    <img src="${imageUrl}" alt="终点货物照片 ${index + 1}" onclick="showLargePreview('${imageUrl}')">
                                </div>
                            `).join('')}
                            ${order.pid.images.length > 3 ? `<div class="photo-preview-item" style="display: flex; align-items: center; justify-content: center; background: #f0f0f0; color: #999; font-size: 12px;">+${order.pid.images.length - 3}</div>` : ''}
                        </div>
                    `;
                }
                
                ordersHtml += `
                    <div class="order-card">
                        <div class="order-header">
                            <div>
                                <div class="order-number">${order.order_num || order.id}</div>
                               
                            </div>
                            <span class="order-status ${statusInfo.class}">${statusInfo.text}</span>
                        </div>
                        
                        <div class="order-content">
                            <div class="order-section">
                                <div class="section-title">起点货物信息</div>
                                <div class="company-info">
                                    <div class="company-name">${order.company || '--'}</div>
                                    <div class="weight-info">货物重量: <span class="weight-value">${order.heavy ? order.heavy + 'kg' : '--'}</span></div>
                                </div>
                                ${startImagesHtml}
                            </div>
                            
                            <div class="order-section">
                                <div class="section-title">终点货物信息</div>
                                ${order.pid ? `
                                    <div class="company-info">
                                        <div class="company-name">${order.pid.company || '--'}</div>
                                        <div class="weight-info">货物重量: <span class="weight-value">${order.pid.heavy ? order.pid.heavy + 'kg' : '--'}</span></div>
                                    </div>
                                    ${endImagesHtml}
                                ` : '<div style="color: #999; font-size: 14px;">暂无终点信息</div>'}
                            </div>
                        </div>
                        
                        <div class="order-actions">
                            <button class="detail-btn" onclick="viewOrderDetail('${order.id}')">查看订单详情</button>
                        </div>
                    </div>
                `;
            });
            
            if (append) {
                orderList.innerHTML += ordersHtml;
            } else {
                orderList.innerHTML = ordersHtml;
            }
        }

        // 加载订单数据
        async function loadOrders(page = 1, append = false) {
            if (isLoading) return;
            
            isLoading = true;
            
            if (page === 1) {
                document.getElementById('orderList').innerHTML = `
                    <div class="loading-state">
                        <div class="loading-spinner"></div>
                        正在加载订单数据...
                    </div>
                `;
            } else {
                document.getElementById('loadingMore').style.display = 'block';
            }
            
            try {
                let obj = {
                    openid: localStorage.getItem('wechat_openid'),
                    page: page,
                    limit: pageSize
                };
                
                let res = await getOrders(obj);
                console.log(res);
                
                const orders = res.data.data || [];
                
                if (!orders || orders.length === 0) {
                    if (page === 1) {
                        document.getElementById('orderList').innerHTML = `
                            <div class="empty-state">
                                <div class="empty-icon">📦</div>
                                <div class="empty-text">暂无订单数据</div>
                            </div>
                        `;
                    } else {
                        hasMore = false;
                        document.getElementById('noMoreData').style.display = 'block';
                    }
                } else {
                    // 保存订单数据
                    if (append) {
                        allOrders = [...allOrders, ...orders];
                    } else {
                        allOrders = orders;
                    }
                    
                    // 渲染订单列表
                    renderOrderList(orders, append);
                    
                    // 检查是否还有更多数据
                    if (orders.length < pageSize) {
                        hasMore = false;
                        document.getElementById('noMoreData').style.display = 'block';
                    } else {
                        hasMore = true;
                    }
                }
                
                currentPage = page;
                
            } catch (error) {
                console.error('加载订单失败:', error);
                if (page === 1) {
                    document.getElementById('orderList').innerHTML = `
                        <div class="empty-state">
                            <div class="empty-icon">❌</div>
                            <div class="empty-text">加载失败，请刷新页面重试</div>
                        </div>
                    `;
                } else {
                    weui.toast('加载更多失败', {
                        className: 'weui-toast_warn',
                        duration: 2000
                    });
                }
            } finally {
                isLoading = false;
                document.getElementById('loadingMore').style.display = 'none';
            }
        }

        // 滚动加载更多
        function handleScroll() {
            // 检查是否滚动到底部
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            const windowHeight = window.innerHeight;
            const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            
            // 距离底部100px时触发加载
            if (scrollTop + windowHeight >= scrollHeight - 100) {
                if (hasMore && !isLoading) {
                    loadOrders(currentPage + 1, true);
                }
            }
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', async function() {
            // 初始加载订单数据
            await loadOrders(1);
            
            // 添加订单按钮点击事件
            document.getElementById('addOrderBtn').addEventListener('click', function() {
                addStartOrder();
            });
            
            // 添加滚动事件监听
            window.addEventListener('scroll', handleScroll);
        });
    </script>
</body>
</html>